package com.xjzd.pattern.responsibility.pipeline;

import java.text.DecimalFormat;

public class Pipeline {

    public static class HandlerChainContext {
        private HandlerChainContext next;
        private final AbstractHandler handler;

        public HandlerChainContext(AbstractHandler handler) {
            this.handler = handler;
        }

        void handle(Object arg) {
            this.handler.doHandle(this, arg);
        }

        void runNext(Object arg) {
            if (this.next != null) {
                this.next.handle(arg);
            }
        }
    }

    public HandlerChainContext context = new HandlerChainContext(new AbstractHandler() {

        @Override
        void doHandle(HandlerChainContext context, Object arg) {
            System.out.println("折扣前：" + arg);
            context.runNext(arg);
        }
    });

    public void addLast(AbstractHandler handler) {
        HandlerChainContext current = context;
        while (current.next != null) {
            current = current.next;
        }
        current.next = new HandlerChainContext(handler);
    }

    public void requestProcess(Object arg) {
        context.handle(arg);
    }

    public static abstract class AbstractHandler {
        abstract void doHandle(HandlerChainContext context, Object arg);
    }

    public static class Handler1 extends AbstractHandler {

        @Override
        void doHandle(HandlerChainContext context, Object arg) {
            System.out.println("--首次购买打9折！");
            arg = new DecimalFormat("0.00").format(Double.parseDouble(arg.toString()) * 0.9);
            System.out.println("折扣后的金额：" + arg);
            context.runNext(arg);
        }
    }

    public static class Handler2 extends AbstractHandler {

        @Override
        void doHandle(HandlerChainContext context, Object arg) {
            System.out.println("--满200减20！");
            if (Double.parseDouble(arg.toString()) >= 200) {
                arg = Double.parseDouble(arg.toString()) - 20;
                System.out.println("折扣后的金额：" + arg);
                context.runNext(arg);
            } else {
                System.out.println("不满足折扣条件，折扣结束：" + arg);
            }
        }
    }

    public static class Handler3 extends AbstractHandler {

        @Override
        void doHandle(HandlerChainContext context, Object arg) {
            System.out.println("--第二件减10元！");
            arg = Double.parseDouble(arg.toString()) - 10;
            System.out.println("折扣后的金额：" + arg);
            context.runNext(arg);
        }
    }

    public static void main(String[] args) {
        Pipeline pipeline = new Pipeline();
        pipeline.addLast(new Handler1());
        pipeline.addLast(new Handler2());
        pipeline.addLast(new Handler3());

        pipeline.requestProcess(300);
    }
}
